<?php
/*
 * @Descripttion: 
 * @version: 1.0
 * @Author: Sam
 * @Date: 2020-10-20 10:37:46
 * @LastEditors: Sam
 * @LastEditTime: 2020-12-16 17:50:36
 */


namespace app\http\middleware;


use app\models\user\User;
use app\models\user\UserToken;
use app\Request;
use exceptions\AuthException;
use interfaces\MiddlewareInterface;
use repositories\UserRepository;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;

/**
 * token验证中间件
 * Class AuthTokenMiddleware
 * @package app\http\middleware
 */
class AuthTokenMiddleware implements MiddlewareInterface
{
    public function handle(Request $request, \Closure $next, bool $force = true)
    {
        $authInfo = null;
        $token    = trim($request->param('token'));
        try {
            $authInfo = UserRepository::parseToken($token);
        } catch (AuthException $e) {
            if ($force)
                return json(['code'=>$e->getCode(),'msg'=>$e->getMessage()]);
        }

        if (!is_null($authInfo)) {
            Request::macro('user', function () use (&$authInfo) {
                return $authInfo['user'];
            });
            Request::macro('tokenData', function () use (&$authInfo) {
                return $authInfo['tokenData'];
            });
        }
        Request::macro('isLogin', function () use (&$authInfo) {
            return !is_null($authInfo);
        });
        Request::macro('uid', function () use (&$authInfo) {
            return is_null($authInfo) ? 0 : $authInfo['user']->id;
        });

        return $next($request);
    }
}